package pl.edu.pk.mech.kkbus.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pl.edu.pk.mech.kkbus.component.ExternalEmailSender;
import pl.edu.pk.mech.kkbus.model.User;
import pl.edu.pk.mech.kkbus.repository.UserDAO;

@Service
public class UserService
{
    
    @Autowired
    UserDAO userDAO;
    
    @Autowired
    ExternalEmailSender emailSender;
    
    public User loadUserByEmail(String email) {
    	return userDAO.loadUserByEmail(email);
    }
    
    public boolean ifEmailExisting(String email) {
    	return userDAO.ifEmailExisting(email);
    }
    
    public List<User> loadUserByRole(String role) {
    	return userDAO.loadUserByRole(role);
    }
    
    public List<User> loadUserDUPA(ArrayList<Long> listId) {
    	return userDAO.loadUserDUPA(listId);
    }
    
    public boolean deleteUser(long id){
    	return userDAO.deleteUser(id);
    }
    
    public boolean banUser(long id, boolean ban){
    	return userDAO.banUser(id, ban);
    }

    public List<User> getUsers() {
    	return userDAO.getUsers();
    }    

    public boolean createUser(User user) {
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        user.setHash(DigestUtils.md5Hex(String.valueOf(new Date()) + "pHe1Ux7kJA")); // salt
        
        boolean result = userDAO.createOrUpdateUser(user);
        
        if(result == true) {
            // hardcoded
            String message = "Link do aktywacji: http://localhost:8080/#user/activate/" + user.getHash();
            emailSender.send(user.getEmail(), "KKBus - Aktywacja Konta", message);
            
            return true;
        } else {
            return false;
        }
    }
    
    public boolean updateUser(User user) {
        return userDAO.updateUser(user);
    }
    
    public boolean editUser(User user) {
    	return userDAO.updateUser(user);
    }

    public User getUser(long id) {
    	return userDAO.getUser(id);
    }
    
    public boolean activateUser(String hash) {
        User user = userDAO.getUserByHash(hash);
        
        if(user == null) {
            return false;
        } else {
            return userDAO.setEnableUser(user);
        }
    }
}